<template>
  <div id="systemLogTableContent">
    <a-tabs v-model:activeKey="editActiveKey">
      <a-tab-pane key="1" tab="系统日志" :forceRender="true">
        <div class="a-scroll">
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="业务日志" :forceRender="true">
        <div id="a-scroll" class="a-scroll">
          <div id="fetchStatisticsEventTypeLogList" class="canvas"></div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="3" tab="审计日志" :forceRender="true">
        <div class="a-scroll">
          <div id="fetchStatisticsResultLogList" class="canvas"></div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" tab="安全日志" :forceRender="true">
        <div class="a-scroll">
        </div>
      </a-tab-pane>
    </a-tabs>

    <!-- 搜索头部 -->
    <div class='logStatistics-header'>
      <div class="logStatistics-header-left">
        <div class="time">
          <span>操作时间：</span>
          <date-range-picker v-model:value="selectTimeRange" :valueFormat="valueFormat" :showTime="false"
            :disabledInfo="disabledInfo" @change="fetchLogList()"></date-range-picker>
        </div>
      </div>
      <div class="searchName">
        <a-input v-model:value="searchName" placeholder="请输入用户名称" style="width: 192px;height:32px">
          <template #suffix>
            <i class="iconfont icon-search" @click="fetchLogList()"></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- log的table表格 -->
    <baseTable :columns="columns.systemLogColumns" :dataSource="configData.records" :isShowPagination="isShowPagination"
      :total="configData.total" @changePage="changePage" :isSelect="true" :scroll="scroll" :rowSelection="1">
      <template #bodyCell="{ column, text, record }">

        <template v-if="column.dataIndex == 'uri'">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <div
          v-for="item in ['logType', 'eventType', 'logLevel', 'operateType', 'requestResult', 'operateUser', 'subEventType', 'responseTime', 'clientIp', 'createTime']">
          <template v-if="column.dataIndex === item">
            <span v-text="getRecordValue(column.dataIndex, record)"></span>
          </template>
        </div>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: detailAble }" @click="detailRecord(record)">
            详情
          </a>
        </template>
      </template>
    </baseTable>
    <!-- 详情弹窗 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      :isCancleBtn='isCancleBtn' @handleCancle="isVisible = false">
      <template v-slot:body>
        <div class="logDetail_item" v-for="item in recordeDetail">
          <span class="logDetail_item_left">{{ item.title }}：</span>
          <span
            :class="item.dataIndex == 'requestResult' && item.value == '成功' ? 'logDetail_item_right success' :
              item.dataIndex == 'requestResult' && item.value == '失败' ? 'logDetail_item_right err' : 'logDetail_item_right'">{{
    item.value
  }}</span>
        </div>
      </template>

    </base-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/systemConfig/columnsName";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import request from "@/api/index";
import dateRangePicker from "@/components/picker/dateRangePicker.vue"
import baseModal from "@/components/modal/baseModal.vue";
import {routerPerm} from '@/utils/common';
// TS
interface dataSourceType {
  [propName: string]: any;
}
//data
const detailAble = ref<boolean>(false);
//头部搜索部分
const searchName = ref('');
const valueFormat = ref('YYYY-MM-DD');
const selectTimeRange = ref<(string | number)[]>([]);//选择时间范围
const disabledInfo = reactive({//日期禁选
  type: 2,
  startDays: 0,
});
//tab页签相关数据
const editActiveKey = ref<string | number>('1');
//日志表格数据
const isShowPagination = true; // 是否需要配分页器
let configData = ref<dataSourceType>({ total: 0, size: 10, records: [] });
let scroll: dataSourceType = reactive({ y: '', isFixed: false })
const reqTelListOption = ref({//控制分页数据请求的变量集合
  pageNumber: 0,
  pageSize: 10,
  tplType: 1
})
// 模态框
const modAlProps: dataSourceType = reactive({
  width: "M",
  title: "日志详情",
});
const recordeDetail = ref<dataSourceType[]>([])
const isVisible = ref<Boolean>(false);
let buttons = ref<dataSourceType[]>([]);
let isCancleBtn = ref<Boolean>(true);
//watch

watch(() => editActiveKey.value, (newVal, oldVal) => {
  nextTick(() => {
    if (newVal != oldVal) {
      fetchLogList(newVal)
    }
  })
})
watch(() => selectTimeRange.value, (newVal, oldVal) => {
  if (newVal && newVal.length == 0 || !newVal) {
    fetchLogList();
  }
})
//methods
//获取日志数据
const fetchLogList = (key: string | number = '') => {
  nextTick(() => {
    let params = {
      type: key || editActiveKey.value,
      pageNumber: key ? 0 : reqTelListOption.value.pageNumber,
      pageSize: key ? 10 : reqTelListOption.value.pageSize,
      endDate: selectTimeRange.value ? selectTimeRange.value[1] : null,
      beginDate: selectTimeRange.value ? selectTimeRange.value[0] : null,
      operateUser: searchName.value,
    }
    request.fetchStatisticsSysLogsList(params).then((res: dataSourceType) => {
      let reqData = res;
      configData.value.total = reqData.total;
      configData.value.size = reqData.size;
      reqData.records.forEach((item: dataSourceType) => {
        item.uri = `[${item.method}]${item.uri}`
      })
      configData.value.records = reqData.records || [];
      nextTick(() => {
        scroll.y = getTableScroll(130, "systemLogTableContent", 46).y;
        scroll.isFixed = getTableScroll(130, "systemLogTableContent", 46).isFixed;
      });
    });
  })
}
const detailRecord = (record: dataSourceType) => {
  if(detailAble.value) return
  let records = JSON.parse(JSON.stringify(record));
  let clientMachineInfo = JSON.parse(record.clientMachineInfo ? record.clientMachineInfo : '{}');
  recordeDetail.value = JSON.parse(JSON.stringify(columns.systemLogColumns));
  let otherData = [
    {
      title: '操作系统',
      dataIndex: 'os',
    },
    {
      title: '浏览器名称',
      dataIndex: 'browser',
    }, {
      title: '用户代理',
      dataIndex: 'userAgent',
    }, {
      title: '请求参数',
      dataIndex: 'paramData',
    }
  ]
  recordeDetail.value.splice(recordeDetail.value.length - 1, 1);
  recordeDetail.value = recordeDetail.value.concat(otherData);
  if (record.clientMachineInfo) {
    for (let item in clientMachineInfo) {
      records[item] = clientMachineInfo[item];
    }
  }
  recordeDetail.value.forEach((data: dataSourceType) => {
    for (let item in records) {
      if (item == data.dataIndex) {
        data.value = getRecordValue(item, records);
      }
    }
  })
  isVisible.value = true;

}
// 将record中的数字转化成文案
const getRecordValue = (key: string, record: dataSourceType) => {
  if (key == 'logType') { // '1:信息 2:警告'
    return record[key] == '1' ? '信息' : '警告'
  } else if (key == 'eventType') { //1:系统 2:业务
    return record[key] == '1' ? '系统' : '业务'
  } else if (key == 'logLevel') {//日志级别(1:高 2:中 3:低)
    return record[key] == '1' ? '高' : record[key] == '2' ? '中' : '低'
  }
  else if (key == 'requestResult') {// 请求结果(1:成功 2:失败)
    return record[key] == '1' ? '成功' : '失败'
  } else if (key == 'operateType') {//操作类型(1:查询 2:新增 3:修改 4:删除 5:导出 6:导入 7:上传 8:下载 9:登录 10:退出)
    return record[key] == '1' ? '查询' :
      record[key] == '2' ? '新增' :
        record[key] == '3' ? '修改' :
          record[key] == '4' ? '删除' :
            record[key] == '5' ? '导出' :
              record[key] == '6' ? '导入' :
                record[key] == '7' ? '上传' :
                  record[key] == '8' ? '下载' :
                    record[key] == '9' ? '登录' : '退出'

  } else if (key == 'responseTime') {
    return record[key] + '毫秒'
  } else {
    return record[key]
  }
}
// 获取分页的改变
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let { pageCurrent, pageSize } = data;
  reqTelListOption.value.pageNumber = pageCurrent;
  reqTelListOption.value.pageSize = pageSize;
  fetchLogList();
};
//mounted
onMounted(() => {
  routerPerm().includes('detailAble') ? detailAble.value = false : detailAble.value = true;
  fetchLogList();
})
</script>

<style lang="less" scoped>
.ant-tabs-content {
  flex-direction: column;
  height: calc(100% - 24px);
}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
#systemLogTableContent {
  background-color: #fff;
  width: 100%;
  height: calc(100% - 88px);
  padding: 16px;
  box-sizing: border-box;
  position: relative;

  .logStatistics-header {
    width: 100%;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .logStatistics-header-left {
      display: flex;
      align-items: center;
    }

    .time {
      margin-right: 16px;
      font-size: 14px;
    }

    .searchName {
      font-size: 14px;
      color: #333;
      margin-left: 16px;
    }
  }
}
</style>
<style lang="less">
#systemLogTableContent .ant-table-wrapper table>thead>tr>th:nth-child(1) {
  padding-left: 16px;
}

#systemLogTableContent .ant-table-wrapper table>tbody>tr>td:nth-child(1) {
  padding-left: 16px;
  padding-right: 16px;
}

.logDetail_item {
  display: flex;
  margin-top: 16px;
  width: 100%;
  font-size: 14px;

  .logDetail_item_left {
    width: 84px;
    text-align: right;
    margin-right: 12px;
  }

  .logDetail_item_right {
    flex: 1;
    line-height: 20px;
    color: #333;
  }

  .success {
    color: rgb(21, 184, 17)
  }

  .err {
    color: rgb(173, 4, 21)
  }

}

.logDetail_item:nth-of-type(1) {
  margin-top: 0px;
}
</style>